package com.edu.demo.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.Digester;
import com.edu.demo.entity.UserBean;
import com.edu.demo.dao.IRegisterDao;
import com.edu.demo.error.costom.PhoneNumberAlreadyExistsException;
import com.edu.demo.service.IRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author XYH
 * date 2024-03-09
 */

@Service
public class RegisterServiceImpl implements IRegisterService {

    @Autowired
    private IRegisterDao registerDao;

    @Override
    public int registerByEmail(UserBean userBean) {
        return registerDao.insertUser(userBean);
    }

    @Override
    public boolean registerByPhone(UserBean userBean) {
        if (registerDao.selectByPhone(userBean) != null) {
            //手机号已存在异常
            throw new PhoneNumberAlreadyExistsException();
        }
        //得到md5
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        //盐值 截取0-20位
        String salt = IdUtil.simpleUUID().substring(0, 20);
        //设置盐值
        md5.setSalt(salt.getBytes());
        //消化盐值 转为16进制 digest:消化 Hex:16进制
        String md5Pass = DigestUtil.md5Hex(userBean.getPassword());
        System.out.println("md5Pass = " + md5Pass);
        userBean.setPassword(md5Pass);
        userBean.setSalt(salt);

        registerDao.insertUserByPhone(userBean);
        return true;
    }


}
